<?php

use EasyWeChat\Factory;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require_once __DIR__ . '/vendor/autoload.php';

class WeChat
{
    /**
     * @return \EasyWeChat\OfficialAccount\Application
     */
    public static function Handle(): \EasyWeChat\OfficialAccount\Application
    {
        $config = [
            'app_id' => 'wxfc06cf257aee00c7',
            'secret' => '7e0cd671178ce39090e8164e384f839c',

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

        ];
        return Factory::officialAccount($config);
    }

}


// Instantiate App
$app = AppFactory::create();

// Add error middleware
$app->addErrorMiddleware(true, true, true);
// Add routes
$app->get('/auth', function (Request $request, Response $response) {

    $args=$request->getQueryParams();
    $host = $args['host'];
    $token = isset($args['token']) ? $args['token'] : '';


    $url=$request->getUri()->getScheme().'://'.$request->getUri()->getHost();
    $redirectUrl = WeChat::Handle()->oauth->scopes(['snsapi_userinfo'])
        ->redirect(sprintf('%s/callBack?host=%s&token=%s', $url, $host, $token));
    header('Location: ' . $redirectUrl);
    exit;
});

$app->get('/callBack', function (Request $request, Response $response) {
    $params = $request->getQueryParams();
    $host = $params['host'];
    $token = $params['token'];
    $code = isset($params['code']) ? $params['code'] : '';
    if (empty($code)) {
        $response->getBody()->write('code not found');
        return $response;
    }
    $user = WeChat::Handle()->oauth->userFromCode($code);
    $openId = $user->getId();
    file_put_contents('./lists/' . $openId . '.ss', serialize($user->getRaw()));
    $redirectUrl=sprintf('%s?token=%s&openid=%s',urldecode($host),$token,$openId);
    header('Location: ' . $redirectUrl);
    exit;
});
$app->get('/getInfo/{openId}', function (Request $request, Response $response, $args) {
    $openId = $args['openId'];
    $data = file_get_contents('./lists/' . $openId . '.ss');
    if(empty($data)){
        return result([
            'code' => -1,
            'msg' => 'data not',
        ], $response);
    }
    return result([
        'code' => 200,
        'msg' => '',
        'data' => unserialize($data),
    ], $response);

});
function result($data, $response)
{
    $payload = json_encode($data);
    $response->getBody()->write($payload);
    return $response
        ->withHeader('Content-Type', 'application/json');
}

$app->run();